package pers.jc.util;

import java.util.Timer;
import java.util.TimerTask;

public abstract class JCTimer {
	private final Timer timer = new Timer();
	
	public JCTimer loop(long interval) {
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				try {
					JCTimer.this.run();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, interval, interval);
		return this;
	}
	
	public JCTimer loop(long interval, long delay) {
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				try {
					JCTimer.this.run();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, delay, interval);
		return this;
	}

	public JCTimer once (long delay) {
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				try {
					JCTimer.this.run();
				} catch (Exception e) {
					e.printStackTrace();
				}
				timer.cancel();
			}
		}, delay);
		return this;
	}
	
	public void cancel() {
		timer.cancel();
	}
	
	public abstract void run();
}
